<?php
    
    namespace App\Http\Controllers\Order;
    
    use App\Models\Cart;
    use App\Models\Goods;
    use App\Models\Order;
    use App\Models\OrderList;
    use App\Models\Product;
    use App\Http\Controllers\Controller;
    
    class OrderController extends Controller
    {
        //接收订单信息,并写入数据库
        //订单添加
        public function addOrder($address, $total, $id)
        {
            //将订单生成交给消息队列来完成
//           { $user = auth()->user()->id;
//            AddOrderJob::dispatch($address, $id, $user);}
//            寻找下表最大的订单
            $ids = explode(',', $id);
            $carts = Cart::whereIn('id', $ids)->with('getGoods', 'getProducts')->get()->toArray();
            $totals = 0;
            foreach ($carts as $cart) {
                $totals = $totals + $cart['number'] * $cart['get_goods']['price'];
            }
            $order = Order::create([
                'orderNumber' => md5(time()),
                'total' => $totals,
                'address' => $address,
                'status' => 0,
                'user_id' => auth()->id(),
            ]);
            //再添加到订单列表里
            foreach ($carts as $cart) {
                $orderList = OrderList::create([
                    'order_id' => $order->id,
                    'goods_id' => $cart['goods_id'],
                    'product_id' => $cart['product_id'],
                    'number' => $cart['number'],
                    'user_id' => auth()->id(),
                ]);
            }
            foreach ($carts as $cart) {
                $product = Product::find($cart['product_id']);
                $product->update(['inventory' => $product['inventory'] - $cart['number']]);
                $cartss = Cart::where('id', $cart['id'])->first();
                $cartss->delete();
            }
            $order = Order::where('user_id', auth()->id())->orderBy('id', 'DESC')->first();
            return redirect()->route('order.order.pay', $order);
        }
        
        //微信支付
        public function pay(Order $order)
        {
//            dd($order['orderNumber']);
            require_once public_path('weixinPay/lib/WxPay.Api.php');
            require_once public_path('weixinPay/example/WxPay.NativePay.php');
            $notify = new \NativePay();
            $input = new \WxPayUnifiedOrder();
            $input->SetBody("猪猪女孩"); //设置支付页面头部信息
            $input->SetAttach($order['orderNumber']); //非常重要的一个值,放在最后
            $input->SetOut_trade_no("sdkphp123456789" . date("YmdHis")); //设置商户系统的订单号
            $input->SetTotal_fee('1'); //订单总金额,只能是总数,单位是分
//        $input->SetTime_start(date("YmdHis"));
//        $input->SetTime_expire(date("YmdHis", time() + 600));
//        $input->SetGoods_tag("test");
            $input->SetNotify_url(asset('/order/order/notify')); //回调请求地址
            $input->SetTrade_type("NATIVE"); //交易类型
            $input->SetProduct_id("123456789");
            $result = $notify->GetPayUrl($input);
            $url2 = $result["code_url"];
            $orderId = $order->id;
            return view('order.order.pay', compact('url2', 'orderId'));
            
        }
        
        public function notify()
        {
            //从服务器上获取微信服务器发来的消息
            $xml = file_get_contents('php://input');
            if ($xml) {
                $data = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
                file_put_contents('data.php', var_export($data, true));
                // 判断是否支付成功,如果支付成功,获取对应的订单号,将对应订单数据改成1或者已支付
                if ($data->result_code == 'SUCCESS' && $data->return_code == 'SUCCESS') {
                    // 获取订单号
                    $orderId = $data->attach;
                    // 找到对应订单号的订单数据,并将status改成1
                    $order = Order::where('orderNumber', $orderId)->first();
                    $order->update(['status' => 1]);
                    // 最后我们需要给微信服务器一个响应,代表着我们接收到了它发来的消息
                    $returnXml = '<xml>
    <return_code><![CDATA[SUCCESS]]></return_code>
    <return_msg><![CDATA[OK]]></return_msg>
    </xml>';
                    file_put_contents('a.php', $returnXml);
                    return $returnXml;
                }
            }
        }
        
        public function checkStatus($orderId)
        {
            $order = Order::where('id', $orderId)->first();
            if ($order['status']) {
                return ['valid' => 1, 'message' => '付款成功'];
            } else {
                return ['valid' => 0, 'message' => '付款未成功'];
            }
        }
        
        //付款成功的页面
        public function paySuccess()
        {
            $good = Goods::get();
            return view('order.order.paySuccess', compact('good'));
        }
        
        public function orderList()
        {
            
            $order = OrderList::where('user_id', auth()->id())->with('getGoods')->with('getOrders')->get()->toArray();
            return view('order.order.orderList', compact('order'));
        }
    }
